package com.lzm.toolfx.utils;

import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;

import java.util.List;

public class HBoxNodeDragUtil {

    public static void addNodeDragListener(Label label,HBox box,Node node){
        new DragListener(label,box,node).enableDrag(node);
    }

    public static void addAllDragListener(Label label,HBox box, List<Node> nodeList){
        nodeList.forEach(node -> {
            new DragListener(label,box,node).enableDrag(node);
        });
    }

    static class DragListener implements EventHandler<MouseEvent> {
        private static double boxXOffset = 0;
        private static double boxYOffset = 0;

        private double xOffset = 0;
        private double yOffset = 0;
        private static HBox box;
        private Node node;
        private Label label;

        public DragListener(Label label,HBox box,Node node) {
            this.box = box;
            this.label = label;
            this.node = node;
            boxXOffset = box.getLayoutX();
            boxYOffset = box.getLayoutY();
        }

        @Override
        public void handle(MouseEvent event) {
            event.consume();
            int index = box.getChildren().indexOf(event.getSource());
            Node pre = box.getChildren().get(index-1);
            Node after = box.getChildren().get(index+1);
            if (event.getEventType() == MouseEvent.MOUSE_PRESSED) {
                xOffset = event.getX();
                yOffset = event.getY();
            } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
                node.setTranslateX((node.getTranslateX()+event.getX() - xOffset));
                if(node.getTranslateX()+event.getX() - xOffset > after.getLayoutBounds().getWidth()){
                    box.getChildren().remove(index);
                    box.getChildren().add(index+1,node);
                    node.setTranslateX(0);
                }else if(node.getTranslateX()+event.getX() - xOffset < pre.getLayoutBounds().getWidth()){
                    box.getChildren().remove(index);
                    box.getChildren().add(index-1,node);
                    node.setTranslateX(0);
                }
                //node.setTranslateY((node.getTranslateY()+event.getY() - yOffset));
            }
            //
            Platform.runLater(()->{
                label.setText("X: "+node.getLayoutBounds().getWidth()+"\nY "+node.getLayoutBounds().getHeight());
            });
        }

        public void enableDrag(Node node) {
            node.setOnMousePressed(this);
            node.setOnMouseDragged(this);
        }
    }
}
